<?php

namespace app\service;

use app\model\Room;
use app\model\User;

class WebSocketService
{
    private static $instance = null;
    private $redis;

    private function __construct()
    {
        $this->redis = RedisService::getInstance();
    }

    public static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 发送用户进入房间消息
     */
    public function sendUserJoinedMessage($roomId, $userId)
    {
        try {
            $user = User::find($userId);
            if (!$user) {
                error_log('用户不存在: ' . $userId);
                return false;
            }

            // 获取房间信息并包含排序后的用户列表
            $room = \app\model\Room::find($roomId);
            if (!$room) {
                error_log('房间不存在: ' . $roomId);
                return false;
            }

            // 确保房间人数是最新的
            $room->refresh();
            $room->updateCurrentPlayers();
            $room->refresh(); // 再次刷新以获取更新后的人数

            // 刷新所有 RoomUser 模型以确保获取最新分数
            $roomUsers = \app\model\RoomUser::where('room_id', $roomId)
                ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                ->get();
            foreach ($roomUsers as $roomUser) {
                $roomUser->refresh(); // 刷新每个用户的状态以获取最新分数
            }

            // 获取排序后的用户列表（确保获取最新分数）
            $sortedUsers = $this->getSortedRoomUsers($room);
            
            // 添加详细日志，记录用户列表
            error_log('sendUserJoinedMessage - 房间ID: ' . $roomId . ', 用户ID: ' . $userId . ', 用户数量: ' . count($sortedUsers));
            foreach ($sortedUsers as $sortedUser) {
                error_log("sendUserJoinedMessage - 用户: ID={$sortedUser['id']}, 昵称={$sortedUser['nickname']}, 分数={$sortedUser['current_score']}");
            }

            $message = [
                'type' => 'user_joined',
                'room_id' => $roomId,
                'message' => $user->nickname . ' 进入了房间',
                'user' => [
                    'id' => $user->id,
                    'nickname' => $user->nickname,
                    'avatar' => $user->avatar
                ],
                'users' => $sortedUsers, // 包含排序后的完整用户列表
                'room_info' => [
                    'id' => $room->id,
                    'room_code' => $room->room_code,
                    'current_players' => $room->current_players,
                    'max_players' => $room->max_players,
                    'status' => $room->status
                ], // 包含房间最新信息（包括人数）
                'timestamp' => time()
            ];

            error_log('准备发送用户进入消息: ' . json_encode($message, JSON_UNESCAPED_UNICODE));
            $result = $this->broadcastToRoom($roomId, $message);
            error_log('用户进入消息发送结果: ' . ($result ? '成功' : '失败'));
            return $result;
        } catch (\Exception $e) {
            error_log('发送用户进入消息失败: ' . $e->getMessage());
            error_log('异常文件: ' . $e->getFile());
            error_log('异常行号: ' . $e->getLine());
            error_log('堆栈跟踪: ' . $e->getTraceAsString());
            return false;
        }
    }

    /**
     * 发送用户离开房间消息
     */
    public function sendUserLeftMessage($roomId, $userId)
    {
        $user = User::find($userId);
        if (!$user) {
            return false;
        }

        // 获取房间信息并包含排序后的用户列表
        $room = \app\model\Room::find($roomId);
        if (!$room) {
            error_log('房间不存在: ' . $roomId);
            return false;
        }

        // 确保房间人数是最新的
        $room->refresh();
        $room->updateCurrentPlayers();
        $room->refresh(); // 再次刷新以获取更新后的人数

        // 获取排序后的用户列表（确保获取最新分数）
        $sortedUsers = $this->getSortedRoomUsers($room);

        $message = [
            'type' => 'user_left',
            'room_id' => $roomId,
            'message' => $user->nickname . ' 离开了房间',
            'user' => [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar
            ],
            'users' => $sortedUsers, // 包含排序后的完整用户列表
            'room_info' => [
                'id' => $room->id,
                'room_code' => $room->room_code,
                'current_players' => $room->current_players,
                'max_players' => $room->max_players,
                'status' => $room->status
            ], // 包含房间最新信息（包括人数）
            'timestamp' => time()
        ];

        return $this->broadcastToRoom($roomId, $message);
    }

    /**
     * 发送用户重新加入房间消息
     */
    public function sendUserRejoinedMessage($roomId, $userId)
    {
        $user = User::find($userId);
        if (!$user) {
            return false;
        }

        // 获取房间信息并包含排序后的用户列表
        $room = \app\model\Room::find($roomId);
        if (!$room) {
            error_log('房间不存在: ' . $roomId);
            return false;
        }

        // 确保房间人数是最新的
        $room->refresh();
        $room->updateCurrentPlayers();
        $room->refresh(); // 再次刷新以获取更新后的人数

        // 刷新所有 RoomUser 模型以确保获取最新分数
        $roomUsers = \app\model\RoomUser::where('room_id', $roomId)
            ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
            ->get();
        foreach ($roomUsers as $roomUser) {
            $roomUser->refresh(); // 刷新每个用户的状态以获取最新分数
        }

        // 获取排序后的用户列表（确保获取最新分数）
        $sortedUsers = $this->getSortedRoomUsers($room);
        
        // 添加详细日志，记录用户列表
        error_log('sendUserRejoinedMessage - 房间ID: ' . $roomId . ', 用户ID: ' . $userId . ', 用户数量: ' . count($sortedUsers));
        foreach ($sortedUsers as $sortedUser) {
            error_log("sendUserRejoinedMessage - 用户: ID={$sortedUser['id']}, 昵称={$sortedUser['nickname']}, 分数={$sortedUser['current_score']}");
        }

        $message = [
            'type' => 'user_rejoined',
            'room_id' => $roomId,
            'message' => $user->nickname . ' 回到了房间',
            'user' => [
                'id' => $user->id,
                'nickname' => $user->nickname,
                'avatar' => $user->avatar
            ],
            'users' => $sortedUsers, // 包含排序后的完整用户列表
            'room_info' => [
                'id' => $room->id,
                'room_code' => $room->room_code,
                'current_players' => $room->current_players,
                'max_players' => $room->max_players,
                'status' => $room->status
            ], // 包含房间最新信息（包括人数）
            'timestamp' => time()
        ];

        error_log('准备发送用户重新加入消息: ' . json_encode($message, JSON_UNESCAPED_UNICODE));
        $result = $this->broadcastToRoom($roomId, $message);
        error_log('用户重新加入消息发送结果: ' . ($result ? '成功' : '失败'));
        return $result;
    }

    /**
     * 发送支出记录消息
     */
    public function sendExpenseRecordedMessage($roomId, $fromUserId, $toUserId, $amount, $expenseType = 'score')
    {
        $fromUser = User::find($fromUserId);
        $toUser = User::find($toUserId);
        
        if (!$fromUser || !$toUser) {
            return false;
        }

        // 获取房间所有用户的最新分数（包括排序）
        // 需要刷新模型以确保获取到最新的分数
        $room = \app\model\Room::find($roomId);
        if ($room) {
            $room->refresh(); // 刷新房间模型
            // 刷新所有 RoomUser 模型以确保获取最新分数
            $roomUsers = \app\model\RoomUser::where('room_id', $roomId)
                ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                ->get();
            foreach ($roomUsers as $roomUser) {
                $roomUser->refresh(); // 刷新每个用户的状态以获取最新分数
            }
        }
        $sortedUsers = $room ? $this->getSortedRoomUsers($room) : null;
        
        // 添加日志，记录用户列表和分数
        error_log('sendExpenseRecordedMessage - 房间ID: ' . $roomId . ', 用户数量: ' . ($sortedUsers ? count($sortedUsers) : 0));
        if ($sortedUsers) {
            foreach ($sortedUsers as $user) {
                error_log("用户分数 - ID: {$user['id']}, 昵称: {$user['nickname']}, 分数: {$user['current_score']}");
            }
        }

        // 生成唯一消息ID，用于去重
        $messageId = uniqid('expense_', true);
        
            $message = [
                'id' => $messageId,
                'type' => 'expense_recorded',
                'room_id' => $roomId,
                'from_user' => [
                    'id' => $fromUser->id,
                    'nickname' => $fromUser->nickname
                ],
                'to_user' => [
                    'id' => $toUser->id,
                    'nickname' => $toUser->nickname
                ],
                'amount' => $amount,
                'expense_type' => $expenseType,
                'description' => "{$fromUser->nickname} 支付 {$amount} 积分给 {$toUser->nickname}",
                'users' => $sortedUsers, // 包含所有用户的最新分数
                'timestamp' => time()
            ];

        // 添加日志，记录发送的消息内容（包含users字段）
        error_log('sendExpenseRecordedMessage - 准备发送消息: ' . json_encode($message, JSON_UNESCAPED_UNICODE));
        
        // 发送支出记录消息（消息中已包含所有用户的最新分数列表）
        $result = $this->broadcastToRoom($roomId, $message);
        error_log('sendExpenseRecordedMessage - 消息发送结果: ' . ($result ? '成功' : '失败'));
        return $result;
    }

    /**
     * 发送积分支付消息
     */
    public function sendScoreTransferMessage($roomId, $fromUserId, $toUserId, $amount, $description = null, $transactionId = null)
    {
        $fromUser = User::find($fromUserId);
        $toUser = User::find($toUserId);
        
        if (!$fromUser || !$toUser) {
            error_log('积分支付消息发送失败：用户不存在');
            return false;
        }

        // 如果没有提供描述，则自动生成
        if (!$description) {
            $description = "{$fromUser->nickname} 支付 {$amount} 积分给 {$toUser->nickname}";
        }
        
        $message = [
            'type' => 'score_transfer',
            'from_user' => [
                'id' => $fromUser->id,
                'nickname' => $fromUser->nickname,
                'avatar' => $fromUser->avatar ?? ''
            ],
            'to_user' => [
                'id' => $toUser->id,
                'nickname' => $toUser->nickname,
                'avatar' => $toUser->avatar ?? ''
            ],
            'amount' => $amount,
            'expense_type' => 'score',
            'description' => $description,
            'transaction_id' => $transactionId,
            'room_id' => $roomId,
            'timestamp' => time()
        ];

        error_log('发送积分支付消息到房间 ' . $roomId . ': ' . json_encode($message, JSON_UNESCAPED_UNICODE));
        
        // 保存消息到历史记录
        $this->saveMessageToHistory($roomId, $message);
        
        // 广播到房间内所有用户
        return $this->broadcastToRoom($roomId, $message);
    }

    /**
     * 发送分数更新消息
     */
    public function sendScoreUpdateMessage($roomId, $userId, $scoreChange)
    {
        try {
            // 获取用户最新分数，刷新模型以确保获取最新数据
            $roomUser = \app\model\RoomUser::where('room_id', $roomId)
                ->where('user_id', $userId)
                ->first();
            
            if (!$roomUser) {
                return false;
            }
            
            // 刷新用户分数模型以获取最新值
            $roomUser->refresh();

            // 获取房间所有用户的最新分数（包括排序），确保所有用户都能看到最新的分数
            $room = \app\model\Room::find($roomId);
            if ($room) {
                $room->refresh(); // 刷新房间模型
                // 刷新所有 RoomUser 模型以确保获取最新分数
                $roomUsers = \app\model\RoomUser::where('room_id', $roomId)
                    ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
                    ->get();
                foreach ($roomUsers as $ru) {
                    $ru->refresh(); // 刷新每个用户的状态以获取最新分数
                }
            }
            $sortedUsers = $room ? $this->getSortedRoomUsers($room) : null;

            $message = [
                'id' => uniqid('score_update_', true),
                'type' => 'scoreUpdated',
                'room_id' => $roomId,
                'user_id' => $userId,
                'new_score' => $roomUser->current_score,
                'score_change' => $scoreChange,
                'users' => $sortedUsers, // 包含所有用户的最新分数
                'timestamp' => time()
            ];

            return $this->broadcastToRoom($roomId, $message);
        } catch (\Exception $e) {
            error_log('发送分数更新消息失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送房间状态变化消息
     */
    public function sendRoomStatusChangedMessage($roomId, $statusData)
    {
        $message = [
            'id' => uniqid('room_status_', true),
            'type' => 'room_status_changed',
            'room_id' => $roomId,
            'status' => $statusData['status'] ?? 'finished',
            'message' => $statusData['message'] ?? '房间状态已变化',
            'current_players' => $statusData['current_players'] ?? 0,
            'timestamp' => time()
        ];

        return $this->broadcastToRoom($roomId, $message);
    }

    /**
     * 发送房间结算消息
     */
    public function sendRoomSettlementMessage($roomId, $settlementData, $message = '房间结算完成')
    {
        // 获取房间信息，确保包含房间状态
        $room = \app\model\Room::find($roomId);
        
        $message = [
            'type' => 'room_settlement',
            'room_id' => $roomId,
            'message' => $message,
            'time' => date('H:i'),
            'settlement_data' => $settlementData,
            'room_info' => [
                'id' => $room ? $room->id : $roomId,
                'room_code' => $room ? $room->room_code : '',
                'status' => $room ? $room->status : 'finished',
                'current_players' => $room ? $room->current_players : 0,
                'max_players' => $room ? $room->max_players : 0
            ], // 包含房间状态信息，前端可以检测并强制离开
            'timestamp' => time()
        ];

        return $this->broadcastToRoom($roomId, $message);
    }


    /**
     * 向房间广播消息
     */
    private function broadcastToRoom($roomId, $message)
    {
        try {
            // 确保消息包含唯一ID
            if (!isset($message['id'])) {
                $message['id'] = uniqid('msg_', true);
            }
            
            // 确保消息包含时间戳
            if (!isset($message['timestamp'])) {
                $message['timestamp'] = time();
            }
            
            // 清理消息ID，确保Redis键名安全
            $cleanMessageId = preg_replace('/[^a-zA-Z0-9_\-\.]/', '_', $message['id']);
            
            // 使用消息ID作为去重键，避免重复发送
            $dedupKey = "message_dedup:{$roomId}:{$cleanMessageId}";
            
            // 检查消息是否已经发送过（10秒内去重）
            if ($this->redis->getClient()->exists($dedupKey)) {
                error_log('WebSocket消息已存在，跳过重复发送: ' . $cleanMessageId);
                return false;
            }
            
            // 设置去重标记
            $this->redis->getClient()->setex($dedupKey, 10, 1);
            
            // 准备发布数据
            $publishData = [
                'room_id' => $roomId,
                'message' => $message,
                'timestamp' => time()
            ];
            
            // 确保数据可以正确序列化
            $jsonData = json_encode($publishData, JSON_UNESCAPED_UNICODE);
            if ($jsonData === false) {
                error_log('WebSocket消息序列化失败: ' . json_last_error_msg());
                return false;
            }
            
            // 验证JSON数据
            if (empty($jsonData)) {
                error_log('WebSocket消息序列化后为空');
                return false;
            }
            
            // 同时使用Redis List和lpush两种方式（兼容Windows环境）
            $roomKey = "room_message:{$roomId}";
            
            // 方式1：存储到Redis List（用于轮询）
            $this->redis->getClient()->lpush($roomKey, $jsonData);
            $this->redis->getClient()->expire($roomKey, 3600); // 1小时过期
            
            // 存储消息到历史记录（只保存需要保留的关键消息类型）
            $this->saveMessageToHistory($roomId, $message);
            
            // 方式2：使用lpush到公共队列替代publish（兼容Windows环境）
            error_log('准备发布消息到Redis队列: ' . $jsonData);
            $result = $this->redis->getClient()->lpush('room_messages_queue', $jsonData);
            if ($result === false) {
                error_log('Redis队列推送消息失败');
                return false;
            }
            error_log('Redis队列推送消息成功，队列长度: ' . $result);
            
            error_log('WebSocket消息已成功发布到房间 ' . $roomId . ': ' . $cleanMessageId);
            return true;
        } catch (\Exception $e) {
            error_log('WebSocket广播消息失败: ' . $e->getMessage());
            error_log('异常文件: ' . $e->getFile());
            error_log('异常行号: ' . $e->getLine());
            error_log('堆栈跟踪: ' . $e->getTraceAsString());
            error_log('消息内容: ' . json_encode($message, JSON_UNESCAPED_UNICODE));
            return false;
        }
    }
    
    /**
     * 将消息保存到历史记录
     */
    private function saveMessageToHistory($roomId, $message)
    {
        try {
            // 只保存关键消息类型到历史记录
            $saveToHistoryTypes = [
                'user_joined', 
                'user_rejoined', 
                'user_left', 
                'expense_recorded', 
                'room_settlement',
                'scoreUpdated',
                'score_transfer'
            ];
            
            $messageType = $message['type'] ?? '';
            
            // 检查消息类型是否需要保存到历史记录
            if (!in_array($messageType, $saveToHistoryTypes)) {
                return;
            }
            
            // 准备历史消息数据（移除不必要的字段，减小存储大小）
            $historyMessage = $message;
            
            // 对于某些消息类型，进行特殊处理以减少存储大小
            switch ($messageType) {
                case 'user_joined':
                case 'user_rejoined':
                case 'user_left':
                    // 只保留必要的用户信息
                    if (isset($historyMessage['user']) && is_array($historyMessage['user'])) {
                        $historyMessage['user'] = array_intersect_key(
                            $historyMessage['user'], 
                            ['id' => 1, 'nickname' => 1, 'avatar' => 1]
                        );
                    }
                    break;
                
                case 'expense_recorded':
                    // 只保留必要的费用记录信息
                    $historyMessage = array_intersect_key(
                        $historyMessage, 
                        ['id' => 1, 'type' => 1, 'from_user' => 1, 'to_user' => 1, 
                         'amount' => 1, 'expense_type' => 1, 'timestamp' => 1]
                    );
                    break;
            }
            
            // 序列化历史消息
            $historyJson = json_encode($historyMessage, JSON_UNESCAPED_UNICODE);
            if ($historyJson === false) {
                error_log('历史消息序列化失败: ' . json_last_error_msg());
                return;
            }
            
            // 保存到Redis列表，只保留最近50条消息
            $historyKey = "room_history:{$roomId}";
            $this->redis->getClient()->lpush($historyKey, $historyJson);
            
            // 只保留最近50条消息
            $this->redis->getClient()->ltrim($historyKey, 0, 49);
            
            // 设置过期时间为24小时
            $this->redis->getClient()->expire($historyKey, 86400);
            
            error_log('消息已保存到房间 ' . $roomId . ' 的历史记录，类型: ' . $messageType);
        } catch (\Exception $e) {
            error_log('保存消息到历史记录失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取房间待发送消息
     */
    public function getRoomMessages($roomId)
    {
        try {
            $key = "room_message:{$roomId}";
            $messages = $this->redis->getClient()->lrange($key, 0, -1);
            $this->redis->getClient()->del($key); // 删除已读取的消息
            
            return array_map(function($message) {
                return json_decode($message, true);
            }, $messages);
        } catch (\Exception $e) {
            error_log('获取房间消息失败: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * 发送结算通知消息
     */
    public function sendSettlementNotification($roomId, $remainingTime)
    {
        $message = [
            'id' => uniqid('settlement_notification_', true),
            'type' => 'settlementNotification',
            'room_id' => $roomId,
            'remaining_time' => $remainingTime,
            'message' => "⏰ 房间将在 {$remainingTime} 后自动结算，请做好准备！",
            'timestamp' => time()
        ];

        return $this->broadcastToRoom($roomId, $message);
    }

    /**
     * 获取房间用户列表并统一排序（用于连接时的全量刷新）
     * 这是一个公开方法，供WebSocketServer在用户连接时调用
     */
    public function getSortedRoomUsersForConnect($room)
    {
        return $this->getSortedRoomUsers($room);
    }

    /**
     * 获取房间用户列表并统一排序
     * 确保所有客户端看到的用户顺序一致
     */
    private function getSortedRoomUsers($room)
    {
        // 获取所有活跃用户
        // 直接从数据库重新查询，避免使用缓存的关联关系，确保获取最新数据
        $roomUsers = \app\model\RoomUser::where('room_id', $room->id)
            ->where('status', \app\model\RoomUser::STATUS_ACTIVE)
            ->with('user')
            ->get();
        
        // 重新从数据库查询每个用户的分数，确保获取最新值
        foreach ($roomUsers as $roomUser) {
            // 重新查询以确保获取最新的current_score
            $freshRoomUser = \app\model\RoomUser::find($roomUser->id);
            if ($freshRoomUser) {
                $oldScore = $roomUser->current_score;
                $roomUser->current_score = $freshRoomUser->current_score;
                if ($oldScore != $roomUser->current_score) {
                    error_log("用户分数已更新 - RoomUser ID: {$roomUser->id}, User ID: {$roomUser->user_id}, 旧分数: {$oldScore}, 新分数: {$roomUser->current_score}");
                }
            }
        }

        // 分离房主和其他用户
        $owner = null;
        $otherUsers = [];

        foreach ($roomUsers as $roomUser) {
            $userData = [
                'id' => $roomUser->user->id,
                'nickname' => $roomUser->user->nickname,
                'avatar' => $roomUser->user->avatar,
                'current_score' => $roomUser->current_score,
                'joined_at' => $roomUser->joined_at->format('Y-m-d H:i:s'),
                'is_owner' => $roomUser->user->id === $room->created_by,
                'room_user_id' => $roomUser->id, // 添加room_user_id用于排序
                'joined_at_timestamp' => $roomUser->joined_at->timestamp // 添加时间戳用于排序
            ];

            if ($roomUser->user->id === $room->created_by) {
                $owner = $userData;
            } else {
                $otherUsers[] = $userData;
            }
        }

        // 其他用户按加入时间排序（joined_at字段）
        usort($otherUsers, function($a, $b) {
            // 首先按加入时间排序
            $timeCompare = $a['joined_at_timestamp'] - $b['joined_at_timestamp'];
            if ($timeCompare !== 0) {
                return $timeCompare;
            }
            // 如果时间相同，按用户ID排序确保稳定性
            return $a['id'] - $b['id'];
        });

        // 构建最终排序结果：房主在第一位，其他用户按加入顺序排列
        $sortedUsers = [];
        if ($owner) {
            $sortedUsers[] = $owner;
        }
        $sortedUsers = array_merge($sortedUsers, $otherUsers);

        // 移除临时字段
        foreach ($sortedUsers as &$user) {
            unset($user['room_user_id']);
            unset($user['joined_at_timestamp']);
        }

        return $sortedUsers;
    }

    /**
     * 发送茶饭设置消息
     */
    public function sendTeaMealSettingsMessage($roomId, $userId, $teaMealLimit, $teaMealPercentage, $teaMealMode = 'percentage', $teaMealFixedAmount = 0)
    {
        try {
            $user = User::find($userId);
            if (!$user) {
                error_log('用户不存在: ' . $userId);
                return false;
            }

            // 根据模式生成不同的消息
            $messageText = '';
            if ($teaMealMode === 'percentage') {
                $messageText = "房主设置了茶饭上限 {$teaMealLimit} 分，扣除比例 {$teaMealPercentage}%";
            } else {
                $messageText = "房主设置了茶饭上限 {$teaMealLimit} 分，固定茶饭费 {$teaMealFixedAmount} 分";
            }

            $message = [
                'type' => 'tea_meal_settings',
                'message' => $messageText,
                'data' => [
                    'user_id' => $userId,
                    'user_nickname' => $user->nickname,
                    'tea_meal_limit' => $teaMealLimit,
                    'tea_meal_percentage' => $teaMealPercentage,
                    'tea_meal_mode' => $teaMealMode,
                    'tea_meal_fixed_amount' => $teaMealFixedAmount
                ]
            ];

            return $this->broadcastToRoom($roomId, $message);
        } catch (\Exception $e) {
            error_log('发送茶饭设置消息失败: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 发送茶饭费扣除消息
     */
    public function sendTeaMealDeductionMessage($roomId, $userId, $deductedAmount, $winAmount)
    {
        try {
            $user = User::find($userId);
            if (!$user) {
                error_log('用户不存在: ' . $userId);
                return false;
            }

            $message = [
                'type' => 'tea_meal_deduction',
                'message' => "{$user->nickname} 赢 {$winAmount} 分，自动扣除茶饭费 {$deductedAmount} 分",
                'data' => [
                    'user_id' => $userId,
                    'user_nickname' => $user->nickname,
                    'win_amount' => $winAmount,
                    'deducted_amount' => $deductedAmount
                ]
            ];

            return $this->broadcastToRoom($roomId, $message);
        } catch (\Exception $e) {
            error_log('发送茶饭费扣除消息失败: ' . $e->getMessage());
            return false;
        }
    }
}
